#include <iostream>
#include <windows.h>
#include <string>

using namespace std;

int main() {
    std::string programPath = "E:/Project/Repositories/cpp/cpp/httpserver/dist/py/dist/ws/ws.exe";
    std::string commandLineArgs = "\"{\\\"allowed_origins\\\": [\\\"http://127.0.0.1:6660\\\"]}\"";

    STARTUPINFO startupInfo;
    PROCESS_INFORMATION processInfo;
    ZeroMemory(&startupInfo, sizeof(startupInfo));
    ZeroMemory(&processInfo, sizeof(processInfo));
    startupInfo.cb = sizeof(startupInfo);

    // 启动另一个程序
    if (!CreateProcess(NULL, (LPSTR)(programPath + " " + commandLineArgs).c_str(), NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo)) {
        std::cout << "Failed to create process: " << GetLastError() << std::endl;
        return 1;
    }

    // 打印子进程的进程ID
    std::cout << "Child process ID: " << processInfo.dwProcessId << std::endl;

    // 监听消息
    while (true) {
        // 检查子进程是否已经退出
        DWORD exitCode;
        if (GetExitCodeProcess(processInfo.hProcess, &exitCode) && exitCode != STILL_ACTIVE) {
            break;
        }

        // 读取子进程输出
        char buffer[1024];
        DWORD bytesRead;
        if (ReadFile(processInfo.hProcess, buffer, sizeof(buffer) - 1, &bytesRead, NULL) && bytesRead > 0) {
            buffer[bytesRead] = '0';
            std::cout << buffer << std::endl;
        }

        Sleep(100); // 可以适当调整等待时间
    }

    cout << 1323 << endl;

    // 关闭句柄
    CloseHandle(processInfo.hProcess);
    CloseHandle(processInfo.hThread);

    return 0;
}